<template>
  <login ref="logins"
         submit-text="微信绑定"
         :wechat="false"
         @submit="handleSubmit"></login>
</template>

<script>
export default {
  data () {
    return {
      openid: '',
    }
  },
  created () {
    const code = this.$route.query.code;
    if (code) {
      const loading = this.$loading({
        lock: true,
        text: '正在加载中，请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$httpajax.get('/login/wechat', {
        params: {
          code: code
        }
      }).then(res => {
        loading.close();
        const data = res.data.data || {};
        if (data.username) {
          this.$store.commit('setUser', data.username);
          this.$message.success('login success!')
          this.goLogin();
        } else {
          this.openid = data;
          this.$nextTick(() => {
            this.$refs.logins.box = true;
            this.$message.error('微信未绑定，请先绑定企业账号')
          })
        }
      })
    } else {
      this.$message.error('微信登录错误，返回首页')
      this.goHome();
    }
  },
  methods: {
    handleSubmit (form) {
      this.$httpajax.get('/login/wechatbind', {
        params: {
          username: form.username,
          password: form.password,
          openid: this.openid
        }
      }).then(() => {
        this.goLogin();
      })
    },
    goLogin () {
      opener.location.reload();
      window.close();
    },
    goHome () {
      window.close();
    },
  }
}
</script>

<style>
</style>